package com.link.base.base.accnt.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.link.base.base.accnt.DmpField;
import com.link.base.base.accnt.dao.mybatis.mapper.AccountMapper;
import com.link.base.base.accnt.model.*;
import com.link.base.base.approval.model.Flow;
import com.link.base.base.approval.service.FlowService;
import com.link.base.base.cmqres.model.CmqRes;
import com.link.base.base.cmqres.service.CmqResService;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.consumer.service.WxConsumerService;
import com.link.base.base.contactinfo.model.ContactInfo;
import com.link.base.base.contactinfo.service.ContactInfoService;
import com.link.base.base.esb.service.LinkBaseDataApiService;
import com.link.base.base.fund.model.BillDetailModel;
import com.link.base.base.fund.model.DealerAccount;
import com.link.base.base.fund.service.DealerAccountService;
import com.link.base.base.invloc.model.Invloc;
import com.link.base.base.invloc.service.InvlocService;
import com.link.base.base.mpconfig.model.Mp;
import com.link.base.base.mvg.dao.mybatis.accnt.mapper.AccntCompanyMvgMapper;
import com.link.base.base.mvg.dao.mybatis.accnt.mapper.AccntOrgMvgMapper;
import com.link.base.base.mvg.dao.mybatis.accnt.mapper.AccntPostnMvgMapper;
import com.link.base.base.mvg.model.Mvg;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.base.base.orgnization.service.OrgnizationService;
import com.link.base.base.product.model.PriceList;
import com.link.base.base.product.service.PriceListService;
import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserService;
import com.link.base.basic.dao.mybatis.mapper.BasicCommonMapper;
import com.link.base.basic.model.ListOfValue;
import com.link.base.basic.service.BasicCommonService;
import com.link.base.core.RSAUtils.SecretKeyUtil;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.base.wechat.common.service.WxCommonService;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxsubscriber.model.Subscriber;
import com.link.base.wechat.wxsubscriber.service.WxSubscriberService;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.mq.util.MqUtil;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.InvalidAlgorithmParameterException;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @date: 2018/11/7 16:26
 * @version 1.0
 */

@Service("accountService")
public class AccountServiceImpl extends BasicServiceImpl<Account> implements AccountService {
    private static final Logger logger = LogManager.getLogger(AccountServiceImpl.class);

    @Resource
    @Qualifier("accountMapper")
    private AccountMapper accountMapper;
    @Resource
    private BasicCommonMapper basicCommonMapper;
    @Resource
    private CmqResService cmqResService;
    @Resource
    private UserService userService;
    @Resource
    private DealerAccountService dealerAccountService;
    @Resource
    private AccntPostnMvgMapper accntPostnMvgMapper;
    @Resource
    private AccntOrgMvgMapper accntOrgMvgMapper;
    @Resource
    private AccntCompanyMvgMapper accntCompanyMvgMapper;
    @Resource
    private OrgnizationService orgnizationService;
    @Resource
    private PriceListService priceListService;
    @Resource
    private AcctAddressService acctAddressService;
    @Resource
    private WxSubscriberService wxSubscriberService;
    @Resource
    private WxConsumerService wxConsumerService;
    @Resource
    private FlowService flowService;
    @Resource
    private BasicCommonService basicCommonService;
    @Resource
    private InvlocService invlocService;
    @Resource
    private KeyGenerateDao keyGenerateDao;
    @Resource
    private WxPlatformService wxPlatformService;
    @Resource
    private WxCommonService wxCommonService;
    @Resource
    private ContactInfoService contactInfoService;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private LinkBaseDataApiService linkBaseDataApiService;

    /**
     * 经销商
     */
    private String dealer = "DEALER1";

    /**
     * 仓库
     */
    private String store = "STORE";

    /**
     * html title
     */
    private String htmlTableTitle = "<tr class=\"titleTr\">";

    /**
     * html conTr
     */
    private String htmlTableConTr = "<tr class=\"conTr\">";

    /**
     * html table 单元格 width:100px class
     */
    private String htmlTdTitleStyle = "<td width='100px' class=\"titleTd\">";

    /**
     * html table 单元格 末尾标签
     */
    private String htmlTdEnd = "</td>";

    /**
     * html table 行 末尾标签
     */
    private String htmlTrEnd = "</tr>";

    /**
     * html table 单元格 id width class
     */
    private String htmlTdInfo = "<td id=\"accountAmount\" width='100px' class=\"conTd\">";
    /**
     * dmp新建消费者接口路径
     */
    private static final String DMP_CONSUMER_INTERFACE_URL = "/link/cdcPubConsumer/upsert";
    /**消费者来源：营销平台*/
    private static final String SOURCE_CHANNEL_MARKET = "MarketingPlatform";
    /**消费者来源：微信*/
    private static final String SOURCE_CHANNEL_WE_CHAT = "WeChat";

    @Override
    public BasicMapper<Account> getBasicMapper() throws Exception {
        return accountMapper;
    }

    @Override
    public List<Account> selectAccountHierarchy(Account entity) throws Exception {
        entity = selectFirstParentAccount(entity);
        selectAllsubset(entity);
        List<Account> ret = new ArrayList<>();
        ret.add(entity);
        return ret;
    }

    /**
     * 所有子级客户查询
     *
     * @author jianlongwen
     * @date 2019/03/24
     * @param account 客户id
     */
    public void selectAllsubset(Account account) {
        // 遍历数组查询所有子级客户
        Account param = new Account();
        param.setAcctParentId(account.getId());
        // 当前客户所有子级
        List<Account> accountList = accountMapper.selectAccountHierarchy(param);
        account.setAccountList(accountList);
        if (accountList.size() > 0) {
            // 查询所有子级客户是否有子级客户
            for (Account acc : accountList) {
                param.setAcctParentId(acc.getId());
                this.selectAllsubset(acc);
            }
        }
    }

    /**
     * 最上级父客户查询
     *
     * @author jianlongwen
     * @date 2019/03/24
     * @param entity 客户id
     */
    public Account selectFirstParentAccount(Account entity) throws Exception {
        List<Account> list = new ArrayList<>();
        entity = accountMapper.queryById(entity);
        if (null != entity.getAcctParentId()) {
            entity.setId(entity.getAcctParentId());
            return selectFirstParentAccount(entity);
        } else {
            return entity;
        }
    }

    @Override
    public Account preDefaultValue(Account entity) throws Exception {
        Long acctId = entity.getId();
        if (null == acctId) {
            acctId = keyGenerateService.keyGenerate();
            entity.setId(acctId);
        }

        CoreUser user = UserUtil.getUser();
        //将登录人的当前职位设置为客户的默认职位，包括职位mvg
        Long postnId = user.getPostnId();
        if (null != postnId) {
            entity.setPostnId(postnId);
            entity.setPostnName(user.getPostnName());
            Mvg mvgEntity = new Mvg();
            mvgEntity.setId(keyGenerateService.keyGenerate());
            mvgEntity.setMvgParentId(acctId);
            mvgEntity.setMvgSubsetId(postnId);
            accntPostnMvgMapper.insert(mvgEntity);
        }

        //将登录人的当前组织设置为客户的默认组织，包括组织mvg
        Long orgId = user.getOrgId();
        if (null != orgId) {
            entity.setOrgId(orgId);
            entity.setOrgName(user.getOrgName());
            Mvg mvgEntity = new Mvg();
            mvgEntity.setId(keyGenerateService.keyGenerate());
            mvgEntity.setMvgParentId(acctId);
            mvgEntity.setMvgSubsetId(orgId);
            accntOrgMvgMapper.insert(mvgEntity);
        }
        return entity;
    }

    /**
     * 修改状态
     * @param entity
     * @throws Exception
     */
    @Override
    public void statusUpdate(Account entity) throws Exception {
        if (null == entity.getId()) {
            throw new ServiceException("PUBLIC-007");
        }
        if (StringUtils.isBlank(entity.getAcctStatus())) {
            throw new ServiceException("PUBLIC-008");
        }
        accountMapper.statusUpdate(entity);

        /**
         * @author huanglongjian
         * @ 推送客户更新消息到cmq
         */
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Account accountResult = this.queryById(entity);
                String type = accountResult.getAcctType();
                String message1 = "";
                if (dealer.equals(type)) {
                    message1 = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";
                    String message2 = "\"}";
                    String message = message1 + accountResult.getId() + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                } else if (store.equals(type)) {
                    message1 = "StoreSyncl;{\"action\":\"Update\",\"objectId\":\"";
                    String message2 = "\"}";
                    String message = message1 + accountResult.getId() + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    /**
     * 审批回调方法
     * @param objectId
     * @param param1
     * @param param2
     * @param param3
     * @param param4
     * @param param5
     * @throws Exception
     */
    @Override
    public void statusUpdateByApproval(Long objectId, String param1, String param2, String param3, String param4,
                                       String param5) throws Exception {
        Account entity = new Account();
        entity.setId(objectId);
        entity.setAcctStatus(param1);
        statusUpdate(entity);


        /**
         * @author huanglongjian
         * @ 推送客户更新消息到cmq
         */
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if (cmqResList.size() > 0) {
            try {
                Account accountResult = this.queryById(entity);
                String type = accountResult.getAcctType();
                String message1 = "";
                if (dealer.equals(type)) {
                    message1 = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";
                    String message2 = "\"}";
                    String message = message1 + accountResult.getId() + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                } else if (store.equals(type)) {
                    message1 = "StoreSyncl;{\"action\":\"Update\",\"objectId\":\"";
                    String message2 = "\"}";
                    String message = message1 + accountResult.getId() + message2;
                    String topicName = cmqResList.get(0).getQueueName();
                    MqUtil.sendCmqTopic(topicName, message);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }

    /**
     * 经销审核:自动创建该经销商的三个资金账户（余额为0）， 然后新建一个外部用户，其用户名为手机号码。 密码为随机的6位数字。 然后需要给用户发送短信过去
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void dealerAudit(Account entity) throws Exception {
        Account account = queryById(entity);
        String phoneNo = account.getMobilePhone().trim();
        if (StringUtils.isBlank(phoneNo)) {
            throw new ServiceException("PUBLIC-009");
        }
        if (userService.getUserByUsername(phoneNo) != null) {
            throw new ServiceException("PUBLIC-010");
        }
        //创建外部用户
        //生成6位随机数字
        String password = "" + (int) ((Math.random() * 9 + 1) * 100000);
        User newUser = userService.outerPreDefaultValue();
        //将手机号码作为用户名
        newUser.setUsername(phoneNo);
        newUser.setPassword(password);
        newUser.setAcctId(account.getId());
        newUser.setContactPhone(phoneNo);
        newUser.setEmpType("OUTER_EMP");
        newUser.setStatus("NORMAL");
        newUser.setFirstName(account.getContactName());
        newUser.setRole(PropertyUtil.getProperty(RedisConstants.key_outerUserDefaultRole, account.getCorpid()));
        userService.insert(newUser);
        //创建返利账户
        insertDealerAccount(account.getId(), "Return Account");
        //创建保证金账户
        insertDealerAccount(account.getId(), "Deposit Account");
        //创建现金账户
        insertDealerAccount(account.getId(), "Cash Account");
        Map<String, Object> result = sendSMS(password, phoneNo, newUser.getFirstName());
        String suc = "success";
        if ((Boolean) result.get(suc) == false) {
            throw new Exception((String) result.get("message"));
        }
    }

    /**
     * 根据客户ID和账户类型 新建资金账户，并且将余额和初始金额设置为0
     *
     * @param acctId            客户ID
     * @param dealerAccountType 资金账户类型
     * @throws Exception
     */
    private void insertDealerAccount(Long acctId, String dealerAccountType) throws Exception {
        DealerAccount dealerAccount = new DealerAccount();
        dealerAccount.setAccntId(acctId);
        dealerAccount.setInitAmount(0.0);
        dealerAccount.setAmount(0.0);
        //资金账户类型
        dealerAccount.setType(dealerAccountType);
        dealerAccountService.insert(dealerAccount);
    }

    /**
     * 发送密码到指定的手机号码
     *
     * @param password 需发送的密码
     * @param phoneNo  接收信息人的手机号码
     * @param name     对接收信息人的称呼
     * @return
     */
    private Map<String, Object> sendSMS(String password, String phoneNo, String name) {

        LinkedHashMap<String, String> param = new LinkedHashMap<String, String>();
        param.put("name", name);
        param.put("password", password);
        String loginMsgTemplate = PropertyUtil.getCommonProperty(RedisConstants.key_loginMsgTemplate);
        return SendSmsUtil.sendMsg2(phoneNo, loginMsgTemplate, param, "");
    }

    /**
     * 修改主要联系人
     * @param account
     */
    @Override
    public void mainContactUpdate(Account account) {
        accountMapper.mainContactUpdate(account);

        //发送cmq
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList;
        try {
            cmqResList = cmqResService.queryAll(cmqRes);
            if (cmqResList != null && cmqResList.size() > 0) {
                Account accountFull = accountMapper.queryById(account);
                String type = accountFull.getAcctType();
                String message1 = "";
                if (dealer.equals(type)) {
                    message1 = "AccountSyncl;{\"action\":\"Insert\",\"objectId\":\"";
                } else if (store.equals(type)) {
                    message1 = "StoreSyncl;{\"action\":\"Insert\",\"objectId\":\"";
                } else {
                    return;
                }
                String message2 = "\"}";
                String message = message1 + accountFull.getId() + message2;
                String topicName = cmqResList.get(0).getQueueName();
                MqUtil.sendCmqTopic(topicName, message);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * 修改主要合同
     * @param account
     */
    @Override
    public void mainAgrUpdate(Account account) {
        accountMapper.mainAgrUpdate(account);
    }

    /**
     * 插入数据到联系人表
     * @param account
     */
    @Override
    public void copyToContactInsert(Account account) {
        accountMapper.copyToContactInsert(account);
    }

    /**
     * 新建数据到到 客户子页签：单权限表
     * @param account
     */
    @Override
    public void copyToBsScopeInsert(Account account) {
        account.setAttr3(String.valueOf(keyGenerateDao.keyGenerate()));
        accountMapper.copyToBsScopeInsert(account);
    }

    /**
     * 更新客户头信息
     * @param account
     */
    @Override
    public void acctHeaderUpdate(Account account) {
        accountMapper.acctHeaderUpdate(account);

    }

    /**
     * 更新客户详细信息
     * @param account
     */
    @Override
    public void acctDetailUpdate(Account account) {
        accountMapper.acctDetailUpdate(account);
    }

    /**
     * 更新联系人数据
     * @param account
     */
    @Override
    public void copyToContactUpdate(Account account) {
        accountMapper.copyToContactUpdate(account);
    }

    /**
     * 新建拜访记录时选择客户
     * @param entity
     * @return
     */
    @Override
    public List<Account> queryVisitAccountPage(Account entity) {
        return accountMapper.queryVisitAccountPage(entity);
    }

    /**
     * 更新dms公司信息
     * @param account
     */
    @Override
    public void updateDmsCompany(Account account) {
        accountMapper.updateDmsCompany(account);
    }

    /**
     * 查找非子客户及本身
     * @param account
     * @return List
     * @throws Exception
     */
    @Override
    public List<Account> queryAccountListRemoveIdAndChildrenPage(Account account) throws Exception {
        //数据库类型
        String dataBaseType = "mysql";
        if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBaseType)) {
            String str = accountMapper.getChildStr(account);
            account.setAttr6(str);
        }
        return accountMapper.queryAccountListRemoveIdAndChildrenPage(account);
    }

    @Override
    public List<Account> accountTreeList(Account entity) throws Exception {

        //获取根节点Id
        Account c = accountMapper.queryRoot(entity);
        List<Account> accountList = null;
        //数据库类型
        String dataBaseType = "mysql";
        if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBaseType)) {
            String str = accountMapper.getChildStr(c);
            QueryParams qps = new QueryParams();
            qps.setAttr2(entity.getLoginCorpId().toString());
            String[] strs = str.split(",");
            qps.setAttr8(strs);
            accountList = accountMapper.queryChildTreeList(qps);
        } else {
            accountList = accountMapper.queryChildTreeList(c);
        }
        //获取树结构
        List<Account> nodeList = new ArrayList<Account>();
        for (Account c1 : accountList) {
            boolean mark = false;
            for (Account c2 : accountList) {
                if (c1.getAcctParentId() != null && c1.getAcctParentId().equals(c2.getId())) {
                    mark = true;
                    if (c2.getChildren() == null) {
                        c2.setChildren(new ArrayList<Account>());

                    }
                    c2.getChildren().add(c1);
                    break;
                }
            }
            if (!mark) {
                nodeList.add(c1);
            }
        }

        return nodeList;
    }

    /**
     * 根据客户查询子客户
     * @param entity
     * @throws Exception
     */
    @Override
    public void queryTreeByRoot(Account entity) throws Exception {
        treeAccountList(entity);
    }

    private void treeAccountList(Account entity) throws Exception {
        ListOfValue record = new ListOfValue();
        record.setType("ACCT_TYPE");
        record.setVal(entity.getAcctType());
        record = basicCommonMapper.getLovName(record);
        entity.setAcctType(record.getName());

        QueryParams qps = new QueryParams();
        qps.addFilter(new Filter("acctParentId", String.valueOf(entity.getId())));
        qps.setPageFlag(false);
        Account t = (Account) BasicModel.transformClass(Account.class, qps);
        List<Account> tempList = accountMapper.queryByExamplePage(t);
        for (Account temp : tempList) {
            record.setVal(temp.getAcctType());
            record = basicCommonMapper.getLovName(record);
            temp.setAcctType(record.getName());
            treeAccountList(temp);
        }
        entity.setChildren(tempList);
    }

    /**
     * 查询区域客户情况
     * @param account
     * @return List
     * @throws Exception
     */
    @Override
    public List<Account> queryAccountOfDistrictPage(Account account) throws Exception {
        return accountMapper.queryAccountOfDistrictPage(account);
    }

    /**
     * 获得区域客户报表html
     * @param list
     * @return String
     * @throws Exception
     */
    @Override
    public String getAccountReportHtml(List<Account> list) throws Exception {
        StringBuilder title = new StringBuilder("");
        StringBuilder html1 = new StringBuilder("");
        StringBuilder title1 = new StringBuilder("");
        StringBuilder html2 = new StringBuilder("");
        StringBuilder title2 = new StringBuilder("");
        StringBuilder html3 = new StringBuilder("");
        StringBuilder title3 = new StringBuilder("");
        title.append("<div id=\"showTableDiv\" class=\"showTableDiv\">");
        title.append("<table id=\"AccountDistribution-table\" style=\"height: 100%;\" keyFilterDiv=\"keyFilter\">");
        if (list.size() == 0) {
            title1.append(htmlTableTitle);
            html1.append(htmlTableConTr);
            title1.append(htmlTdTitleStyle + "无省份" + htmlTdEnd);
            html1.append(htmlTdInfo + "无客户" + htmlTdEnd);
            html1.append(htmlTrEnd);
            title1.append(htmlTrEnd);
        } else {
            int twelve = 12;
            int twentyFour = 24;
            if (list.size() <= twelve) {
                title1.append(htmlTableTitle);
                html1.append(htmlTableConTr);
                for (int n = 0; n < list.size(); n++) {
                    NumberFormat nf = NumberFormat.getInstance();
                    //nf.setGroupingUsed(false);//设为true则使用分组方式显示数据，即每三位数为一个分组，分组间以英文半角逗号分隔。
                    String amount = nf.format(list.get(n).getTotal());
                    title1.append(htmlTdTitleStyle + list.get(n).getProvince() + htmlTdEnd);
                    html1.append(htmlTdInfo + amount + htmlTdEnd);
                }
                html1.append(htmlTrEnd);
                title1.append(htmlTrEnd);
            } else if (list.size() > twelve && list.size() <= twentyFour) {
                //换行
                title1.append(htmlTableTitle);
                html1.append(htmlTableConTr);
                for (int n = 0; n < twelve; n++) {
                    NumberFormat nf = NumberFormat.getInstance();
                    //nf.setGroupingUsed(false);//设为true则使用分组方式显示数据，即每三位数为一个分组，分组间以英文半角逗号分隔。
                    String amount = nf.format(list.get(n).getTotal());
                    title1.append(htmlTdTitleStyle + list.get(n).getProvince() + htmlTdEnd);
                    html1.append(htmlTdInfo + amount + htmlTdEnd);
                }
                html1.append(htmlTrEnd);
                title1.append(htmlTrEnd);

                title2.append(htmlTableTitle);
                html2.append(htmlTableConTr);
                for (int n = twelve; n < list.size(); n++) {
                    NumberFormat nf = NumberFormat.getInstance();
                    //nf.setGroupingUsed(false);//设为true则使用分组方式显示数据，即每三位数为一个分组，分组间以英文半角逗号分隔。
                    String amount = nf.format(list.get(n).getTotal());
                    title2.append(htmlTdTitleStyle + list.get(n).getProvince() + htmlTdEnd);
                    html2.append(htmlTdInfo + amount + htmlTdEnd);
                }
                html2.append(htmlTrEnd);
                title2.append(htmlTrEnd);
            } else {
                title1.append(htmlTableTitle);
                html1.append(htmlTableConTr);
                for (int n = 0; n < twelve; n++) {
                    NumberFormat nf = NumberFormat.getInstance();
                    //nf.setGroupingUsed(false);//设为true则使用分组方式显示数据，即每三位数为一个分组，分组间以英文半角逗号分隔。
                    String amount = nf.format(list.get(n).getTotal());
                    title1.append(htmlTdTitleStyle + list.get(n).getProvince() + htmlTdEnd);
                    html1.append(htmlTdInfo + amount + htmlTdEnd);
                }
                html1.append(htmlTrEnd);
                title1.append(htmlTrEnd);

                title2.append(htmlTableTitle);
                html2.append(htmlTableConTr);
                for (int n = twelve; n < twentyFour; n++) {
                    NumberFormat nf = NumberFormat.getInstance();
                    //nf.setGroupingUsed(false);//设为true则使用分组方式显示数据，即每三位数为一个分组，分组间以英文半角逗号分隔。
                    String amount = nf.format(list.get(n).getTotal());
                    title2.append(htmlTdTitleStyle + list.get(n).getProvince() + htmlTdEnd);
                    html2.append(htmlTdInfo + amount + htmlTdEnd);
                }
                html2.append(htmlTrEnd);
                title2.append(htmlTrEnd);

                title3.append(htmlTableTitle);
                html3.append(htmlTableConTr);
                for (int n = twentyFour; n < list.size(); n++) {
                    NumberFormat nf = NumberFormat.getInstance();
                    //nf.setGroupingUsed(false);//设为true则使用分组方式显示数据，即每三位数为一个分组，分组间以英文半角逗号分隔。
                    String amount = nf.format(list.get(n).getTotal());
                    title3.append(htmlTdTitleStyle + list.get(n).getProvince() + htmlTdEnd);
                    html3.append(htmlTdInfo + amount + htmlTdEnd);
                }
                html3.append(htmlTrEnd);
                title3.append(htmlTrEnd);
            }
        }
        html1 = title1.append(html1);
        html2 = title2.append(html2);
        html3 = title3.append(html3);

        StringBuilder html = new StringBuilder("");
        html = title.append(html1.toString() + html2.toString() + html3.toString());
        html.append("</table>");
        html.append("</div>");
        String result = "";
        result = html.toString();
        return result;
    }

    /**
     * @Comments 更新主要资金账户
     * @param account 客户Id，资金账户Id
     * @throws Exception
     */
    @Override
    public void mainBillUpdate(Account account) throws Exception {
        accountMapper.mainBillUpdate(account);
    }
    /*
     * 大自然更新客户表更新后的处理暂时用不到，并且在用户未登录的情况下会影响客户信息的更新操作，先做注释处理。
     * */
/*    @Override
    public void afterUpdate(Account account) throws Exception{
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if(cmqResList.size()>0) {
            try {
                String Type = account.getAcctType();
                String message1 = "";
                if("DEALER1".equals(Type)) {
                    message1 = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";
                }
                else if ("STORE".equals(Type)) {
                    message1 = "StoreSyncl;{\"action\":\"Update\",\"objectId\":\"";
                }
                else {
                    return;
                }
                String message2 = "\"}";
                String message = message1+account.getId()+message2;
                String topicName = cmqResList.get(0).getQueueName();
                MqUtil.sendCmqTopic(topicName,message);
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }

    }*/

    @Override
    public void beforUpsert(Account account) {
//      Gson gson = new Gson();
//      String json = gson.toJson(account);
//      System.out.println("Upsert Account: " + json);
//      logger.debug("Upsert Account: " +json);
    }

    /*大自然更新客户表添加客户后的处理暂时用不到，并且在用户未登录的情况下会影响客户信息的添加操作，先做注释处理。*/
/*    @Override
    public void afterInsert(Account account) throws Exception{
        CmqRes cmqRes = new CmqRes();
        List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
        if(cmqResList.size()>0) {
            try {
                String Type = account.getAcctType();
                String message1 = "";
                if("DEALER1".equals(Type)) {
                    message1 = "AccountSyncl;{\"action\":\"Insert\",\"objectId\":\"";
                }
                else if ("STORE".equals(Type)) {
                    message1 = "StoreSyncl;{\"action\":\"Insert\",\"objectId\":\"";
                }
                else {
                    return;
                }
                String message2 = "\"}";
                String message = message1+account.getId()+message2;
                String topicName = cmqResList.get(0).getQueueName();
                MqUtil.sendCmqTopic(topicName, message);
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        }
    }*/


    /**
     * 获取消费者列表
     */
    @Override
    public List<Account> getAccountList(Account t) {

        return accountMapper.getAccountList(t);
    }

    /**
     * 根据客户和组织，初始化客户组织
     * <p>注意："门店(值列表源代码：Terminal)"升级组织时，仅升级组织，不创建和关联价目表</p>
     *
     * @param accnt
     * @param org
     * @throws ServiceException
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void upgradeToOrg(Account accnt, Orgnization org, ListOfValue lov) throws Exception {
        Orgnization newOrg = new Orgnization();
        //用客户ID作为新建的组织的ID
        Long newOrgId = accnt.getId();
        //创建组织
        newOrg.setId(newOrgId);
        //是否有效
        newOrg.setIsEffective("Y");
        newOrg.setParentOrgId(org.getId());
        newOrg.setAcctId(accnt.getId());
        //组织名称=客户名称
        newOrg.setText(accnt.getAcctName());
        //组织编码=客户编码
        newOrg.setOrgCode(accnt.getAcctCode());
        newOrg.setOrgType(lov.getVal());
        //如果客户类型不是"终端门店"，则创建价格表
        String terminal = "Terminal";
        if (!StringUtils.equals(terminal, accnt.getAcctType())) {
            //创建价格头表
            PriceList priceList = createDealerSalePriceHead(accnt, newOrgId);
            newOrg.setPriceListId(priceList.getId());
        }
        orgnizationService.insert(newOrg);

        //accnt.setOrgFlag("Y");
        accnt.setOrgId(newOrgId);
        accountMapper.update(accnt);
    }

    /**
     * 创建经销商的销售价格头表
     * @param account 经销商
     * @param orgId   组织ID
     * @return PriceList
     * @throws Exception
     */
    @Override
    public PriceList createDealerSalePriceHead(Account account, Long orgId) throws Exception {
        if (null == orgId) {
            throw new ServiceException("PUBLIC-004");
        }
        PriceList priceHead = new PriceList();
        priceHead.setPriceListName(account.getAcctName() + "价格表");
        priceHead.setActivated("Y");
        priceHead.setOrgId(orgId);
        //默认人民币
        priceHead.setCurrency("CNY");
        //默认类型为销售价格表
        priceHead.setGener("SalesPriceList");
        //获取1小时前的时间
        Date effStartDate = DateUtil.addTimes(Calendar.HOUR, new Date(), -1);
        priceHead.setEffStartDate(DateUtil.dateToStr(effStartDate, "yyyy-MM-dd HH:mm:ss"));
        priceHead.setEffEndDate(null);
        priceListService.insert(priceHead);
        return priceHead;
    }

    /**
     * 查询指定条件下的客户
     *
     * @param account
     * @return list
     * @throws Exception
     */
    @Override
    public List<Account> queryAllByAccntStatus(Account account) throws Exception {
        return accountMapper.queryAllByAccntStatus(account);
    }

    /**
     * 查询符合生成对账单的客户
     * @param billDetailModel
     * @return List
     * @throws Exception
     */
    @Override
    public List<BillDetailModel> queryAllBillAccntByCondtion(BillDetailModel billDetailModel) throws Exception {
        return accountMapper.queryAllBillAccntByCondtion(billDetailModel);
    }

    /**
     * 获取系统参数配置的虚拟消费者
     *
     * @param corpId
     * @return string
     */
    @Override
    public String getVirtualAccount(Long corpId) {
        LinkRedisClient jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            Map<String, String> privateCfg = jedis.hgetAll(RedisConstants.SYS_PROPERTY_CORP_KEY + corpId);
            String visualAccountID = privateCfg.get("VisualAccountID");
            return StringUtils.isNotBlank(visualAccountID) ? visualAccountID : "";
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    /**
     * 检查消费者是否存在
     *
     * @param account
     * @return account
     * @throws Exception
     */
    @Override
    public Account checkAccount(Account account) throws Exception {
        CoreUser user = UserUtil.getUser();
        Account queryParam = new Account();
        queryParam.setPageFlag(false);
        queryParam.setCorpid(user.getCorpid());
        queryParam.setOrgId(user.getOrgId());
        queryParam.setMobilePhone1(account.getMobilePhone1());

        if (null == account.getId()) {
            Account insertParam = new Account();
            insertParam.setId(keyGenerateService.keyGenerate());
            insertParam.setMobilePhone1(account.getMobilePhone1());
            insertParam.setOrgId(user.getOrgId());
            insertParam.setPostnId(user.getPostnId());
            insertParam.setCorpid(user.getCorpid());
            insertParam.setAcctName(StringUtils.isBlank(account.getAcctName()) ? "门店客户" : account.getAcctName());
            insertParam.setAcctType("ChannelConsumer");
            insertParam.setAcctStatus("Y");
            insertParam.setGender("UNKNOWN");
            insertParam.setAcctChannel("Store");
            insertParam.setAcctStage("PotentialConsumer");
            insertParam.setLogin(user.getUsername());
            insertParam.setDataSource(account.getDataSource());
            this.insert(insertParam);
            return this.queryById(insertParam.getId());
        } else {
            Account updateParam = this.queryById(account.getId());
            return updateParam;
        }
    }

    /**
     * 查询导购姓名列表
     *
     * @param account 客户id
     * @return 导购姓名list
     * @author : LiQun
     * @date : 下午3:06 2018/7/27
     */
    @Override
    public List<String> queryGuideList(Account account) throws Exception {
        List<String> guides = accountMapper.queryGuideList(account);
        return guides;
    }

    /**
     * 通过客户id查询标签列表
     *
     * @author lizt
     * 2017年3月27日
     */
    @Override
    public List<TagItem> queryTagsById(TagItem record) throws Exception {
        // 查询客户标签
        // 1. 如果客户没有关联企点客户,则只查询CRM标签
        // 2. 如果客户关联了企点客户,则通过客户id查询CRM标签,企点openId查询其关联的起点客户的企点标签
        List<TagItem> tList = accountMapper.queryAccountTags(record);
        return tList;
    }

    /**
     * @author : LiQun
     * @date : 下午5:12 2018/4/23
     * @dscription : 更新客户标签
     */

    @Override
    public void updateTagList(ListOfTags list) throws Exception {
        if (list.getList() != null && list.getList().size() > 0) {
            Long id;
            for (TagItem tagItem : list.getList()) {
                id = tagItem.getId();

                if (null == id) {
                    id = keyGenerateService.keyGenerate();
                    tagItem.setId(id);
                }
                // 客户自定义标签
                if ("other_accnt_tag".equals(tagItem.getSources())) {
                    if (ROW_STATUS_INSERT.equals(tagItem.getRow_status())) {
                        // 新建
                        accountMapper.accntTagInsert(tagItem);

                    } else if (ROW_STATUS_DELETE.equals(tagItem.getRow_status())) {
                        // 删除
                        accountMapper.deleteAccnt8TagById(tagItem);
                    }
                } else if ("CRM".equals(tagItem.getSources())) {
                    if (ROW_STATUS_INSERT.equals(tagItem.getRow_status())) {
                        // 新建
                        accountMapper.accntTagInsert(tagItem);

                    } else if (ROW_STATUS_DELETE.equals(tagItem.getRow_status())) {
                        // 删除
                        accountMapper.deleteAccnt8TagById(tagItem);
                    } else if (ROW_STATUS_UPDATE.equals(tagItem.getRow_status()) || StringUtils.isBlank(tagItem.getRow_status())) {
                        // 更新
                        accountMapper.accntTagUpdate(tagItem);
                    }
                }
            }
        }
    }

    /**
     * 查询企点客户的状态数据
     *
     * @author lizt
     * 2017年5月18日
     */
    @Override
    public List<TagItem> queryQdAccntTagGroups(TagGroup entity) throws Exception {
        return accountMapper.queryQdAccntTagGroups(entity);
    }

    /**
     * 查询企点客户的状态数据
     *
     * @author lizt
     * 2017年5月18日
     */
    @Override
    public List<TagItem> queryQdAccntTags(TagItem entity) throws Exception {
        return accountMapper.queryQdAccntTags(entity);
    }

    /**
     * 删除客户标签信息
     *
     * @author lizt
     * 2017年3月29日
     */
    @Override
    public void deleteTagById(TagItem item) throws Exception {
        accountMapper.deleteAccnt8TagById(item);
    }

    /**
     * 消费者修改信息前要校验手机号：（门店来源消费者）
     * 同一个门店内的消费者数据修改，手机号不允许重复
     *
     * @author LiJie
     * @date 2019/3/26 11:21
     * @param entity 消费者对象
     */

    @Override
    public void beforUpdate(Account entity) throws Exception {
        //门店消费者标识
        String store = "Store";
        //来源是门店的进行校验
        if (store.equals(entity.getAttr1())) {
            Account account = new Account();
            account.setAcctChannel(entity.getAcctChannel());
            account.setPageFlag(false);
            List<Account> list = this.queryByExamplePage(account);
            for (int i = 0; i < list.size(); i++) {
                if (null != entity.getMobilePhone1() && entity.getMobilePhone1().equals(list.get(i).getMobilePhone1())
                        && !(entity.getId().equals(list.get(i).getId()))) {
                    throw new ServiceException("PUBLIC-011");
                }
            }
        }
    }

    /**
     * 插入中间表
     *
     * @param entity 客户-识别顾客中间表对象
     * @throws Exception 异常信息
     * @author : LiQun
     * @date : 下午3:57 2018/5/7
     */
    @Override
    public void accountPersonInsert(AccountPerson entity) throws Exception {
        int count = accountMapper.queryAccountPersonById(entity);
        if (count == 0) {
            if (null == entity.getId()) {
                Long id = keyGenerateService.keyGenerate();
                entity.setId(id);
            }
            accountMapper.accountPersonInsert(entity);
        }
    }

    /**
     * 生成客户二维码
     *
     * @author SiYe
     * 2017年8月8日
     */
    @Override
    public Account saveAccnt2CodeInfoNew(Account record) throws Exception {
        //场景ID
        String num8seq = accountMapper.get8NumFromSeq();
        record.setAccntSeq(num8seq);
        //微信二维码的URL
        String barcodeUrl;
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform = wxPlatformService.queryDefaultByCorpid(wxPlatform);
        if (wxPlatform == null || StringUtils.isNull(wxPlatform.getWx_og_id())) {
            throw new ServiceException("ACCT-011");
        }
        try {
            barcodeUrl = wxCommonService.createTempQrCode(wxPlatform.getWx_app_id(), record.getAccntSeq(), "259200");
           // record.setWx2dBarcodeUrl(barcodeUrl);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new Exception("获取二维码异常：" + e.getMessage());
        }
        return record;
    }

    /**
     * 查询客户头像url及更多信息
     *
     * @author ouyangzhenqiang
     * 2017年8月8日
     */
    @Override
    public Account queryUpdWxInfo(Account record) throws Exception {
        String accntSeq = record.getAccntSeq();
        if (!StringUtils.isNull(accntSeq)) {
            Subscriber ssw = wxConsumerService.downloadWxOnRedis(accntSeq);
            if (ssw != null) {
                record.setId(ssw.getAccountId());
                record.setMainWXOpenid(ssw.getOpenid());
                //record.setWxHeadimgurl(ssw.getHeadimgurl());
                record.setAcctName(ssw.getNickname());
                record.setQdNickName(ssw.getNickname());
                record.setGender(ssw.getSex());
                record.setAddress(ssw.getCountry() + ssw.getProvince() + ssw.getCity());
                //record.setWxSubscribeTime(ssw.getSubscribeTimeDate());
                //根据微信openid查询
                Account dbAccount = accountMapper.queryByWxOpenId(record);
                if (dbAccount != null) {
                    record = dbAccount;
                    if (StringUtils.isNull(record.getAcctName())) {
                        record.setAcctName(ssw.getNickname());
                    }
                    if (StringUtils.isNull(record.getQdNickName())) {
                        record.setQdNickName(ssw.getNickname());
                    }
                    if (StringUtils.isNull(record.getGender())) {
                        record.setGender(ssw.getSex());
                    }
                    if (StringUtils.isNull(record.getAddress())) {
                        record.setAddress(ssw.getCountry() + ssw.getProvince() + ssw.getCity());
                    }
                }
            } else {
                record.setMainWXOpenid(null);
            }
        } else {
            record = new Account();
            record.setMainWXOpenid(null);
        }
        return record;
    }

    /**
     * 清空客户微信seq
     */
    @Override
    public void emptyAccntSeq(Account record) throws Exception {
        accountMapper.emptyAccntSeqUpdate(record);
    }

    @Override
    public List<Account> queryByWeixin(Account entity) throws Exception {
        return accountMapper.queryByWeixinPage(entity);

    }

    @Override
    public List<Account> queryWeixinByMobilePhone(Account entity) throws Exception {
        return accountMapper.queryWeixinByMobilePhone(entity);
    }

    /**
     * 根据wxopenid查询客户
     */
    @Override
    public Account queryByWxOpenId(String wxOpenId, Long corpId) throws Exception {
        Account record = new Account();
        record.setMainWXOpenid(wxOpenId);
        record.setCorpid(corpId);
        record.setLoginCorpId(corpId);
        return accountMapper.queryByWxOpenId(record);
    }

    @Override
    public Account queryByWxSeq(Account entity) throws Exception {
        return accountMapper.queryByWxSeq(entity);
    }


    @Override
    public void wxAccountInsertByInterface(Account entity) throws Exception {
        accountMapper.wxAccountInsertByInterface(entity);
    }

    @Override
    public void accountWxOwnOpenIdUpdate(Account entity) throws Exception {
        accountMapper.accountWxOwnOpenIdUpdate(entity);
    }

    @Override
    public void wx2codeUpdate(Account entity) throws Exception {
        accountMapper.wx2codeUpdate(entity);
    }

    @Override
    public Account querySimpleAccntByWxOpenId(String wxOpenId)
            throws Exception {
        Account entity = new Account();
        entity.setMainWXOpenid(wxOpenId);
        return accountMapper.querySimpleAccntByWxOpenId(entity);
    }


    /**
     * 根据小程序openId查询消费者信息
     *
     * @param account
     * @return account
     * @author Lizt
     * @date 2018/7/26
     */
    @Override
    public Account queryConsumerByOpenId(Account account) throws Exception {
        Account record = accountMapper.queryConsumerByOpenId(account);
        return record;
    }

    /**
     * 插入消费者信息，小程序登录接口用
     *
     * @param account
     * @author Lizt
     * @date 2018/7/31
     */
    @Override
    public void addConsumer(Account account) throws Exception {
        // 在客户表增加记录
        account.setId(keyGenerateService.keyGenerate());
        account.setAcctType("ChannelConsumer");
        String createdDate = DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
        account.setCreated(createdDate);
        account.setLastUpdated(createdDate);
        account.setCreatedBy(account.getId());
        account.setLastUpdatedBy(account.getId());
        accountMapper.addConsumer(account);
    }

    /**
     * 重置redis中的sessionkey的值
     *
     * @author LiQun
     * @param jedis           jedis实例
     * @param code            票据
     * @param appEncryptionId app加密id
     * @param session_key     自定义的key
     * @date 2019/3/28 14:44
     */
    private JSONObject resetSessionKey(LinkRedisClient jedis, String code, String appEncryptionId, String session_key) throws Exception {
        Mp mp = userService.getMpConfigInfo(jedis, appEncryptionId);
        String mpAppId = mp.getAppId();
        String mpAppSecret = mp.getAppSecret();
        String mpCorpId = mp.getCorpid() + "";
        if (StringUtils.isBlank(mpAppId) || StringUtils.isBlank(mpAppSecret) || StringUtils.isBlank(mpCorpId)) {
            throw new BasicServiceException("获取小程序参数信息异常!");
        }
        // 获取openId,unionid,sessionkey信息
        JSONObject mpResult = userService.getJsCodeToSession(code, mpAppId, mpAppSecret);
        if (mpResult == null) {
            throw new BasicServiceException("调用微信接口返回信息为空，请检查");
        } else {
            String errcode = "errcode";
            if (mpResult.get(errcode) != null) {
                String errorResult = mpResult.getString("errmsg");
                throw new BasicServiceException(errorResult);
            } else {
                // 会话密钥
                String sessionKey = mpResult.getString("session_key");
                // 将redis中的值重置
                jedis.hset(session_key, "sessionKey", sessionKey);
                jedis.expire(session_key, 7200);
            }
        }
        return mpResult;
    }


    /**
     * 查询当前用户信息
     *
     * @return Account
     * @author Lizt
     * @date 2018/8/20
     */
    @Override
    public Account queryConsumerInfo() throws Exception {
        CoreUser user = UserUtil.getUser();
        if (user == null || user.getId() == null) {
            throw new ServiceException("PUBLIC-012");
        }
        Account account = new Account();
        account.setId(user.getId());
        account = accountMapper.queryById(account);
        return account;
    }

    /***
     * 客户签约提交审批
     *
     * @param accnt
     * @param approvalDetail
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void accntSigningSubmit(Account accnt, String approvalDetail) throws Exception {
        Long selectUserId = 0L;
        String approvalType = "NewAccountSign";
        //创建审批流程
        flowService.createFlow(accnt.getId(), approvalType, selectUserId, accnt.getAcctName(), accnt.getId(), approvalDetail);
        /*修改客户状态为“签约审批中”*/
        accnt.setAcctStatus("SignApproving");
        accountMapper.update(accnt);
    }

    /***
     * 客户签约审批处理-状态修改
     *
     * @param objectId
     * @param param1
     * @param param2
     * @param param3
     * @param param4
     * @param param5
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void accntSigningStatusUpdate(Long objectId, String param1, String param2,
                                         String param3, String param4, String param5) throws Exception {
        /*客户信息*/
        Account queryAccnt = new Account();
        queryAccnt.setId(objectId);
        Account accnt = queryById(queryAccnt);
        if (accnt == null) {
            throw new RuntimeException("查询客户失败！");
        }
        //审批拒绝
        String rejected = "Rejected";
        if (rejected.equals(param1)) {
            /*修改客户【合作状态】为“签约失败”*/
            accnt.setAcctStatus("SignFail");
            accountMapper.update(accnt);
        }
        //审批通过
        String approved = "Approved";
        if (approved.equals(param1)) {
            /*初始化客户信息*/
            initializeAcct(accnt);
            /*修改客户【合作状态】为“合作”*/
            accnt.setAcctStatus("Cooperate");
            accountMapper.update(accnt);
        }
    }


    /**
     * 初始化客户信息
     *
     * @param account
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void initializeAcct(Account account) throws Exception {
        /**
         * 1 创建资金账户
         * 2 创建仓库
         */
        List<ListOfValue> dealerAcctLV = null;
        List<DealerAccount> dealerAcctList = null;
        DealerAccount dealerAcctParam = null;

        List<Invloc> invlocList = null;
        Invloc invlocParam = null;
        List<ListOfValue> invlocLV = null;

        if (null == account.getId()) {
            throw new ServiceException("PUBLIC-003");
        }
        Account acct = queryById(account);
        if (Objects.isNull(acct)) {
            throw new ServiceException("ACCT-012");
        }
        /***
         * 资金账户
         * 根据值列表中配置的个数，来创建资金账户
         * 必传字段
         * accntId: W-30D0527   //当前客户id
         accntName: 张三      //当前客户名称
         type: Cash Account   //独立源代码
         amount: 0.00
         initAmount: 0.00
         */
        //资金值列表
        dealerAcctLV = queryLVByParams("DEALER_ACCOUNT_TYPE", "");
        //初始化资金账户
        if (!dealerAcctLV.isEmpty()) {
            //校验客户资金账户
            dealerAcctParam = new DealerAccount();
            dealerAcctParam.setAccntId(acct.getId());
            dealerAcctList = dealerAccountService.queryByAccountId(dealerAcctParam);
            //如果资金账户不为空
            if (!dealerAcctList.isEmpty()) {
                //资金账户类型集合转换
                List<String> dTypes = dealerAcctList.stream().collect(
                    () -> new ArrayList<>(),
                    (l, d) -> l.add(d.getType()),
                    (ll, l2) -> ll.addAll(l2));
                //筛选出新增的值列表
                dealerAcctLV = dealerAcctLV.stream().filter(d -> {
                    //独立源代码不在里面
                    return !dTypes.contains(d.getVal());
                }).collect(Collectors.toList());
            }
            //创建资金账户
            dealerAcctLV.stream().forEach(n -> {
                DealerAccount newDealAcct = new DealerAccount();
                Long dealAcctId = keyGenerateService.keyGenerate();
                newDealAcct.setId(dealAcctId);
                //客户id
                newDealAcct.setAccntId(acct.getId());
                newDealAcct.setAccountName(acct.getAcctName() + n.getName());
                newDealAcct.setAmount(0.00);
                newDealAcct.setInitAmount(0.00);
                //可用余额
                newDealAcct.setAvailableBalance(0.00);
                newDealAcct.setCurrency(acct.getCurrency());
                /**
                 *资金账户 值列表DEALER_ACCOUNT_TYPE类型下的独立源代码
                 * types = [DEALER_ACCOUNT_TYPE]
                 */
                newDealAcct.setType(n.getVal());
                try {
                    dealerAccountService.insert(newDealAcct);
                } catch (Exception e) {
                    LCLogger.withException(e);
                    //抛出异常
                    throw new BasicServiceException(e);
                }
            });
        }

        //仓库
        invlocParam = new Invloc();
        invlocParam.setOwnerId(acct.getId());
        invlocList = invlocService.queryByAcctId(invlocParam);
        if (invlocList.isEmpty()) {
            //指定仓库一个值列表
            invlocLV = queryLVByParams("INVLOC_TYPE", "WAREHOUSE");
            // 初始化仓库
            if (!invlocLV.isEmpty() && invlocLV.size() == 1) {
                ListOfValue lov = invlocLV.get(0);
                /**
                 * invlocName: 测试02        //当前用户名+仓库分类名称
                 invlocType: WAREHOUSE     //默认仓库值列表类型
                 ownerId: W-30D0527    //客户id
                 ownerName: 张三      //客户名称
                 orgId: 2-225757      //组织id
                 orgName: CRM产品事业部  //组织名称
                 */
                Invloc newInvloc = new Invloc();
                Long invId = keyGenerateService.keyGenerate();
                newInvloc.setId(invId);
                /**
                 * @TODO 仓库名称 = 客户名称+ 值列表分类，默认一个‘仓库’
                 * types = [INVLOC_TYPE]
                 * */
                newInvloc.setInvlocName(acct.getAcctName() + lov.getName());
                //值列表的独立源代码
                newInvloc.setInvlocType(lov.getVal());
                newInvloc.setOwnerId(acct.getId());
                newInvloc.setOwnerName(acct.getAcctName());
                newInvloc.setOrgId(acct.getOrgId());
                newInvloc.setOrgName(acct.getOrgName());
                invlocService.insert(newInvloc);
            }
        }
    }

    /***
     * 通过type 和独立源代码 查看指定值列表
     * @param type   类型
     * @param val    独立源代码
     * @throws Exception
     */
    private List<ListOfValue> queryLVByParams(String type, String val) throws Exception {
        ListOfValue entity = new ListOfValue();
//        entity.setOrderByClause(" seq asc ");
        entity.setActiveFlag("Y");
        entity.setPageFlag(false);
        //类型
        entity.setType(type);
        //独立源代码
        entity.setVal(val);
        return basicCommonService.queryByExamplePage(entity);
    }

    /**
     * 客户签约审批处理-审批成功后更新客户信息和合同信息
     *
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void accntApprovalObjectUpdate(AccountApprovalInfo entity) throws Exception {
        Flow flow = new Flow();
        flow.setId(entity.getApprovalId());
        Flow flowObj = flowService.queryById(flow);
        String currentIsWrite = "Y";
        if (currentIsWrite.equals(flowObj.getCurrentIsWrite())) {
            /*审批详情封装json字符串*/
            String approvalDetail = JSONObject.toJSONString(entity);
            /*审批流程更新*/
            flowObj.setFlowObjDetail(approvalDetail);
            flowService.update(flowObj);
        }
        if (StringUtils.isBlank(flowObj.getNewStepNum())) {
            /*客户信息更新*/
            Account accnt = entity.getAcctObj();
            getBasicMapper().update(accnt);
        }
    }

    /**
     * 微信加密数据解密
     *
     * @author KuangRuifeng
     * @date 2018年11月29日
     * @param sessionKey session_key
     * @param encryptData 加密数据
     * @param iv 加密算法的初始向量
     * @return result 解密之后json数据
     */
    private JSONObject decryptData(String sessionKey, String encryptData, String iv) {
        LinkRedisClient j = null;
        String sessionKeyTemp = "";
        JSONObject result = null;
        try {
            j = RedisUtil.getJedis();
            sessionKeyTemp = j.hget(sessionKey, "sessionKey");
            LCLogger.info().withMessage("Redis中session_key => " + sessionKeyTemp).flush();
        } finally {
            RedisUtil.returnResource(j);
        }
        if (!StringUtils.isBlank(sessionKeyTemp)) {
            try {
                byte[] resultByte = PasswordUtil.decrypt(Base64.decodeBase64(encryptData),
                        Base64.decodeBase64(sessionKeyTemp),
                        Base64.decodeBase64(iv));
                if (null != resultByte && resultByte.length > 0) {
                    String infoStr = new String(resultByte, "UTF-8");
                    LCLogger.info().withMessage("userInfoStr => " + infoStr).flush();
                    result = JsonUtil.toJsonObject(infoStr);
                } else {
                    LCLogger.info().withMessage("解密失败").flush();
                }
            } catch (InvalidAlgorithmParameterException | UnsupportedEncodingException e) {
                LCLogger.withException(e);
            }
        } else {
            LCLogger.info().withMessage("未匹配到redis记录").flush();
        }
        return result;
    }


    @Override
    public List<Account> queryMpStoreByExamplePage(Account temp) throws Exception {
        return accountMapper.queryMpStoreByExamplePage(temp);
    }

    @Override
    public Account queryAccountByPersonId(AccountPerson accountPerson) throws Exception {
        return accountMapper.queryAccountByPersonId(accountPerson);
    }

    @Override
    public List<Account> queryAccountByPersonIdList(List<AccountPerson> list) throws Exception {
        return accountMapper.queryAccountByPersonIdList(list);
    }

    /**
     * 根据一个消费者信息，带出消费者对应所有会员(或电话号码)信息
     * @author wangdawei
     *  Attr1标记是根据会员查还是根据电话号码查
     * @param entity
     * @return List
     */
    @Override
    public List<Account> queryAcctListById(Account entity) throws Exception {
        if (null == entity) {
            throw new ServiceException("ACCT-014");
        }
        List<Account> accountList = new ArrayList<>();
        try {
            String queryType = "mobilePhone";
            Account account = new Account();
            account.setPageFlag(false);
            boolean flag = queryType.equals(entity.getAttr1());
            if (StringUtils.isNotBlank(entity.getMobilePhone1()) && flag) {
                account.setMobilePhone1(entity.getMobilePhone1());
                accountList = accountMapper.queryByExamplePage(account);
            } else {
                accountList.add(entity);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new Exception(e.getMessage());
        }
        return accountList;
    }

    /**
     * 小程序获取到手机号码后更新消费者和会员手机号码信息
     * @author KuangRuifeng
     * @date 2018/12/18
     * @param record 手机号码信息
     * @throws Exception 异常信息
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public Map<String, Object> updMobilePhoneInfo(Account record) throws Exception {
        Map<String, Object> result = new HashMap<>(2);
        CoreUser user = UserUtil.getUser();
        // 根据手机号码和渠道查询消费者
        Account account = new Account();
        account.setMobilePhone1(record.getMobilePhone());
        account.setAcctChannel(user.getMpAppId());
        List<Account> accountList = accountMapper.queryByExamplePage(account);
        if (accountList != null && accountList.size() > 0) {
            // 如果存在，判断是否与当前用户为同一条记录
            if (user.getAcctId().equals(accountList.get(0).getId())) {
                result.put("result", "Y");
                result.put("message", "该手机号已绑定此微信号");
            } else {
                result.put("result", "N");
                result.put("message", "该手机号已绑定其他微信号");
            }
        } else {
            // 不存在，更新当前用户
            Account newAccount = this.queryById(user.getAcctId());
            newAccount.setMobilePhone1(record.getMobilePhone());
            accountMapper.updMobilePhoneInfo(newAccount);
            result.put("result", "Y");
            result.put("message", "已更新");
        }
        return result;
    }

    @Override
    public Account queryAcctAndMember(Account entity) throws Exception {
        return accountMapper.queryAcctAndMember(entity);
    }

    /**
     * 小程序手机号登陆校验
     *
     * @author KuangRuifeng
     * @date 2019/03/14 10:47
     * @param record 手机号码信息
     */
    @Override
    public Map<String, Object> checkMPLoginPhone(Account record) throws Exception {
        Map<String, Object> result = new HashMap<>(2);
        String mobilePhone = record.getMobilePhone();
        Account accountParam = new Account();
        accountParam.setMobilePhone1(mobilePhone);
        accountParam.setAcctType("ChannelConsumer");
        accountParam.setPageFlag(false);
        List<Account> accountList = this.queryByExamplePage(accountParam);
        // 逻辑有问题 后续考虑更改，先保证逻辑能走通
/*        if (accountList.size() > 0) {
            // 如果存在，应该只存在一条这样的记录。判断openid是否相同
            String openid = UserUtil.getUser().getOpenId();
            String openidData = accountList.get(0).getWxOwnOpenId();
            if (openid.equals(openidData)) {
                result.put("result", "Y");
            } else {
                result.put("result", "N");
                result.put("failMessage", "该手机号已绑定其他微信");
            }
        } else {
            // 不存在，判断当前用户是否之前保存有手机号码信息
            Long id = UserUtil.getUser().getId();
            Account account = this.queryById(id);
            if (StringUtils.isBlank(account.getMobilePhone1())) {
                // 更新信息
                account.setMobilePhone1(mobilePhone);
                this.update(account);
                result.put("result", "Y");
            } else {
                if (mobilePhone.equals(account.getMobilePhone1())) {
                    result.put("result", "Y");
                } else {
                    result.put("result", "N");
                    result.put("failMessage", "该微信已绑定其他手机号");
                }
            }
        }*/
        if (accountList.size() > 0) {
            result.put("result", "Y");
        }
        return result;
    }

    @Override
    public Account saveAccountToDmp(Account entity) throws Exception {
        String dmpConsumerUrl = "http://"
                + YmlConstants.getDmpIp() + DMP_CONSUMER_INTERFACE_URL;
        if (StringUtils.isBlank(entity.getId() + "")) {
            entity.setId(keyGenerateService.keyGenerate());
        }
        // 调用DMP接口新增渠道消费者
        String channelConsumer = "ChannelConsumer";
        // 处理标签数据组装长文本
        JSONObject param = JSONObject.parseObject(JSONObject.toJSONString(transformToDmpConsumer(entity)));
        logger.info("Base [消费者]传入接口参数：" + param.toString());
        Map<String, Object> jsonObject = SecretKeyUtil.dmpHttpPostWithDefault(dmpConsumerUrl, param);
        logger.info("DMP [消费者]返回数据：" + jsonObject.toString());
        JSONObject message = null;
        try {
            message = JSONObject.parseObject(jsonObject.get("message").toString());
        } catch (Exception e) {
            logger.error("DMP系统连接失败，当前URL为【" + dmpConsumerUrl + "】");
            throw new BasicServiceException("DMP系统连接失败，当前URL为【" + dmpConsumerUrl + "】");
        }
        boolean requestFail = !(boolean) jsonObject.get("success") || !(boolean) message.get("success");
        if (requestFail) {
            logger.error("DMP系统保存消费者失败：" + message.get("result"));
            throw new BasicServiceException("DMP系统保存消费者失败：" + message.get("result"));
        }
        JSONObject newRowJson = (JSONObject) message.get("newRow");
        Account newRow = transformDmpToLink(newRowJson);
        Account account = queryById(newRow);
        if (account != null) {
            // 营销平台已存在记录，仅更新，当DMP返回数据为未更新的数据时，此时可以同步DMP与营销平台的数据
            this.update(newRow);
        } else {
            this.insert(newRow);
        }
        // 保存父消费者
        JSONObject parentRowJson = (JSONObject)message.get("parentRow");
        if (parentRowJson != null) {
            Account parentRow = transformDmpToLink(parentRowJson);
            if (queryById(parentRow) == null) {
                parentRow.setRow_status(BasicService.ROW_STATUS_INSERT);
                this.upsert(parentRow);
            }
        }
        return newRow;
    }

    /**
     * 将DMP数据转化为link的对象
     *
     * @author NingLanhao
     * @date 2019-04-07 18:27
     * @param jsonObj
     * @return com.link.business.base.accnt.model.Account
     */
    private Account transformDmpToLink(JSONObject jsonObj) {
        Account obj = new Account();
        Class<Account> accountClass = Account.class;
        Field[] fields = accountClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(DmpField.class)) {
                // link字段名
                String name = field.getName();
                // 对应set方法
                String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
                DmpField annotation = field.getAnnotation(DmpField.class);
                // dmp对应字段名，作为map的KEY
                String linkFieldName = annotation.fieldName();
                Object valueObj = jsonObj.get(linkFieldName);
                if (valueObj != null) {
                    // dmp字段值
                    String value = valueObj.toString();
                    try {
                        Method method = accountClass.getMethod(methodName, String.class);
                        method.invoke(obj, new Object[]{value});
                    } catch (NoSuchMethodException e) {
                        throw new BasicServiceException("不存在【" + methodName + "】此方法");
                    } catch (IllegalAccessException e) {
                        throw new BasicServiceException("【" + methodName + "】方法执行失败");
                    } catch (InvocationTargetException e) {
                        throw new BasicServiceException("【" + methodName + "】方法执行失败");
                    }
                }
            }
        }
        obj.setId(Long.parseLong(jsonObj.get("id").toString()));
        obj.setOrgId(Long.parseLong(jsonObj.get("orgId").toString()));
        obj.setPostnId(Long.parseLong(jsonObj.get("postnId").toString()));
        return obj;
    }

    /**
     * 将link中的Account对象做字段映射，提供调用DMP接口的消费者参数
     *
     * @author NingLanhao
     * @param entity 新增客户参数
     * @return
     * @date 2019-03-26 17:06
     */
    private Object transformToDmpConsumer(Account entity) {
        CoreUser user = UserUtil.getUser();
        Map param = new HashMap(30);
        // 标准字段
        param.put("id", entity.getId());
        String orgId = StringUtils.isBlank(entity.getOrgId() + "") ? user.getOrgId() + "" : entity.getOrgId() + "";
        String postnId = StringUtils.isBlank(entity.getPostnId() + "") ? user.getPostnId() + "" : entity.getPostnId() + "";
        if (StringUtils.isBlank(orgId) || StringUtils.isBlank(postnId)) {
            throw new BasicServiceException("请联系管理员维护组织或职位信息");
        }
        param.put("orgId", orgId);
        param.put("postnId", postnId);
        param.put("row_status", entity.getRow_status());
        param.put("srcRowId", entity.getId());
        param.put("srcCreated", entity.getCreated());
        param.put("srcCreatedBy", entity.getCreatedBy());
        param.put("srcLastUpd", entity.getLastUpdated());
        param.put("srcLastUpdBy", entity.getLastUpdatedBy());
        // 已经做过映射的字段
        SecretKeyUtil.DmpParamUtil.transformDmpAnnotationField(entity, param);

        return param;
    }

    /**
     * 仅修改指定字段字段
     *
     * @author NingLanhao
     * @date 2019-04-04 16:46
     * @param old 数据库内原始对象
     * @param notModify 接口传入对象，要保存的信息
     * @return void
     */
    private void updateFieldSelective(Account old,Account notModify) {
        old.setAcctName(notModify.getAcctName());
        old.setGender(notModify.getGender());
        old.setBirthday(notModify.getBirthday());
        if (StringUtils.isBlank(old.getSalesmanId() + "")) {
            old.setSalesmanId(notModify.getSalesmanId());
            old.setPostnId(notModify.getPostnId());
            old.setOrgId(notModify.getOrgId());
        }
    }

    @Override
    public void updateConsumer(Account entity) throws Exception {
        accountMapper.updateConsumer(entity);
    }

    @Override
    public Account queryConsumerById(Long id) throws Exception {
        return accountMapper.queryConsumerById(id);
    }

    /**
     * 微信更新消费者
     *
     * @author huanglongjian
     * @date 2019-10-22 14:19
     * @param
     * @return
     */
    @Override
    public Account wxUpdateAccount(Account account) throws Exception {
        accountMapper.wxUpdateAccount(account);
        return accountMapper.queryById(account);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void accountSubmit(Account entity) throws Exception {
        //A.校验是否保存客户头信息，若未保存则报错：请保存客户信息后再提交；
        Account record = queryById(entity);
        if (record == null) {
            throw new ServiceException("IYUACCT-001");
        }
        //只有客户状态为新建，审批状态为新建或者审批拒绝的正式客户类型才能进行提交 (210524 补充已编码状态 在非审批中都可提交
        String auditStatus = record.getAuditStatus();
        if (!("Customer".equals(record.getAcctType())
                && (("New".equals(record.getAcctStatus())
                && ("New".equals(auditStatus) || "Rejected".equals(auditStatus)))
            || ( "FinEncoded".equals(record.getAcctStatus())
                || ("New".equals(auditStatus) || "Rejected".equals(auditStatus) || "Approved".equals(auditStatus)))))) {
            throw new ServiceException("IYUACCT-002");
        }
        //B.再校验是否填写联系人子页签信息，若未填写则报错：请填写并保存联系人信息后再提交审批；
        ContactInfo contactInfo = new ContactInfo();
        contactInfo.setAccountId(record.getId());
        List<ContactInfo> contactInfoList = contactInfoService.queryByExamplePage(contactInfo);
        if (contactInfoList.size() == 0) {
            throw new ServiceException("IYUACCT-003");
        }
        //C.校验客户附件是否上传，若未上传附件则报错：请上传附件后再提交审批；
        Attachment attachment = new Attachment();
        attachment.setHeadId(record.getId());
        List<Attachment> attachmentList = attachmentService.queryByExamplePage(attachment);
        if (attachmentList.size() == 0) {
            throw new ServiceException("IYUACCT-004");
        }
        if (StringUtils.isNotBlank(entity.getAcctCode()) && "FinEncoded".equals(entity.getAcctStatus())) {
            String approvalType = "NewAccount";
            ObjectMapper mapper = new ObjectMapper();
            String approvalDetail = mapper.writeValueAsString(record);
            //创建审批流程
            flowService.createFlow(record.getId(), approvalType, null, record.getAcctName(), record.getId(), approvalDetail);
            record.setAuditStatus("Approving");
            accountMapper.auditUpdate(record);
        } else {
            String approvalType = "EncodeAccount";
            ObjectMapper mapper = new ObjectMapper();
            String approvalDetail = mapper.writeValueAsString(record);
            //创建审批流程
            flowService.createFlow(record.getId(), approvalType, null, record.getAcctName(), record.getId(), approvalDetail);
            record.setAuditStatus("Approving");
            accountMapper.auditUpdate(record);
        }

    }

    @Override
    public void apprNewAccount(Flow flow, String arg1, String arg2, String arg3, String arg4, String arg5) throws Exception {
        Long acctId = flow.getFlowObjId();
        Long createBy = flow.getCreatedBy();
        Account account = new Account();
        account.setId(acctId);
        account.setAuditStatus(arg1);
        account.setAcctStatus(arg2);
        if ("Approved".equals(arg1)) {
            String flowType = flow.getApprType();
            switch (flowType) {
                case "FreezeAccount":
                    account.setFreezeBy(createBy);
                    break;
                case "ThawAccount":
                    account.setThawBy(createBy);
                    break;
                case "InactiveAccount":
                    account.setUnactBy(createBy);
                    break;
                case "ActiveAccount":
                    account.setActBy(createBy);
                    break;
                default:
                    break;
            }
        }
        accountMapper.auditUpdate(account);

        //客户审批通过生效解冻，冻结后，数据同步至ERP
        if ("Active".equals(account.getAcctStatus()) || "Freezed".equals(account.getAcctStatus())) {
            linkBaseDataApiService.syncAccountInfo(account);
        }
    }

    @Override
    public List<Account> queryAccountListByAcctChange(Account entity) throws Exception {
        return accountMapper.queryAccountListByAcctChange(entity);
    }

    @Override
    public void auditUpdate(Account account) throws Exception {
        accountMapper.auditUpdate(account);
    }

    @Override
    public void accountChangeAppr(AcctChange acctChange) {
        accountMapper.accountChangeAppr(acctChange);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void accountAudit(Account entity) throws Exception {
        String approvalType = entity.getApprovalType();
        Account account = queryById(entity);
        if (account == null) {
            throw new ServiceException("IYUACCT-101");
        }
        switch (approvalType) {
            //校验客户状态（只有生效的不在审批中的客户可以冻结）
            case "FreezeAccount" :
                if (!"Active".equals(account.getAcctStatus()) || "Approving".equals(account.getAuditStatus())) {
                    throw new ServiceException("IYUACCT-102");
                }
                account.setFreezeReason(entity.getFreezeReason());
                account.setFreezeProd(entity.getFreezeProd());
                account.setFreezeRange(entity.getFreezeRange());
                account.setSpecificRange(entity.getSpecificRange());
                break;
            case "InactiveAccount":
                if (!"Active".equals(account.getAcctStatus()) || "Approving".equals(account.getAuditStatus())) {
                    throw new ServiceException("IYUACCT-103");
                }
                account.setUnactReason(entity.getUnactReason());
                break;
            case "ActiveAccount":
                if (!"Inactive".equals(account.getAcctStatus()) || "Approving".equals(account.getAuditStatus())) {
                    throw new ServiceException("IYUACCT-104");
                }
                account.setActReason(entity.getActReason());
                break;
            case "ThawAccount":
                if (!"Freezed".equals(account.getAcctStatus()) || "Approving".equals(account.getAuditStatus())) {
                    throw new ServiceException("IYUACCT-105");
                }
                account.setThawReason(entity.getThawReason());
                account.setFreezeProd(entity.getFreezeProd());
                account.setThawRange(entity.getThawRange());
                account.setSpecificRange(entity.getSpecificRange());
                break;
            default:
                break;
        }

        //后续替换为和OA接口

        ObjectMapper mapper = new ObjectMapper();
        String approvalDetail = mapper.writeValueAsString(account);
        flowService.createFlow(account.getId(), approvalType, null, account.getAcctName(), account.getId(), approvalDetail);
        entity.setAuditStatus("Approving");
        //补充更新冻结相关字段
        accountMapper.auditUpdate(entity);
    }

    @Override
    public List<Account> accountLevelReport(Account entity) throws Exception {
        List<Account> resultList = new ArrayList<>();
        Account account = queryById(entity);
        if (account == null) {
            throw new ServiceException("IYUACCT-100");
        }
        Account entity2 = new Account();
        entity2.setAcctParentId(entity.getId());
        List<Account> list = queryAll(entity2);
        if (list != null && list.size() > 0) {
            account.setChildren(list);
        }
        if (account.getAcctParentId() != null) {
            Account record = new Account();
            record.setName(account.getAcctParentName());
            List<Account> childList = new ArrayList<>();
            childList.add(account);
            record.setChildren(childList);
            resultList.add(record);
        } else {
            resultList.add(account);
        }
        return resultList;
    }

    @Override
    public void updateAcctCode(Account entity) throws Exception {
        //判断客户数据
        Long acctId = entity.getId();
        Account record = queryById(acctId);
        //只有正式的、审批状态为新建或者审批拒绝或者审批成功、待编码的客户可以更新客户编码
        if (!("Customer".equals(record.getAcctType())
                && "Encoded".equals(record.getAcctStatus())
                && ("New".equals(record.getAuditStatus()) || "Rejected".equals(record.getAuditStatus())
                || "Approved".equals(record.getAuditStatus())))) {
            throw new ServiceException("IYUACCT-005");
        }

        Account queryOne = new Account();
        queryOne.setAcctCode(entity.getAcctCode());
        List<Account> accountList = accountMapper.queryByExamplePage(queryOne);
        if (accountList.size() > 0) {
            throw new ServiceException("IYUACCT-006");
        }
        //更新客户编码及状态
        entity.setAcctStatus("FinEncoded");
        accountMapper.acctCodeUpdate(entity);
    }

}
